package tn.bergaoui.openwebapp.wicket.pages;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;

import tn.bergaoui.openwebapp.beans.BaseBean;
import tn.bergaoui.openwebapp.dao.GenericJpaDao;
import tn.bergaoui.openwebapp.wicket.components.ISelectionListener;

/**
 * Shows a list of people.
 * 
 * @author Bergaoui BacemO
 */
public abstract class ListPanel<T extends BaseBean, TDao extends GenericJpaDao<T>>
		extends Panel {

	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected ISelectionListener listener;
	
	public ListPanel(String id, ISelectionListener listener,
			final Component component) {
		super(id);

		this.listener = listener;
		setOutputMarkupId(true);
		loadEntitis();

		final ListView listView = createListView(component);
		add(listView);

		AjaxLink link = new AjaxLink("addPlayer") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				EntityManager entityManager = getGenericDao()
						.getEntityManager();
				entityManager.getTransaction().begin();
				T entity = createDefaultEntity();
				getGenericDao().save(entity);
				entityManager.getTransaction().commit();

				loadEntitis();
				if (target != null)
					target.addComponent(ListPanel.this);
				ListPanel.this.addOrReplace(listView);
			}

		};

		add(link);
		// add(new Label("label", new Model("this is a wicket sample ....")));
	}

	protected abstract ListView createListView(final Component component);

	protected abstract T createDefaultEntity();

	protected List loadEntitis() {
		List resultList = getGenericDao().select();
		return resultList;
	}

	public abstract TDao getGenericDao();

}
